package cn.deschen.app.controller;

import cn.deschen.app.vo.PlanDetailVO;
import cn.deschen.biz.domain.entity.AdPlan;
import cn.deschen.biz.dto.plan.PlanAddDTO;
import cn.deschen.biz.dto.plan.PlanQueryDTO;
import cn.deschen.biz.dto.plan.PlanUpdateDTO;
import cn.deschen.biz.service.AdPlanService;
import cn.deschen.common.api.BizResCode;
import cn.deschen.common.api.CmPage;
import cn.deschen.common.api.CmRes;
import cn.deschen.common.api.CmResCode;
import cn.deschen.common.config.security.UserDetails;
import cn.deschen.common.config.security.UserInfoContext;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @Author hanbin_chen
 * @Description 推广计划控制层
 * @DateTime 2021/06/18
 * @Version V1.0.0
 */
@RestController
@Slf4j
@RequestMapping("/ad/plan")
@Api(tags = "推广计划管理")
public class AdPlanController {

    @Autowired
    private AdPlanService planService;

    @Autowired
    private MapperFacade mapperFacade;

    @ApiOperation("创建推广计划")
    @PostMapping()
    public CmRes<Void> add(@Valid @RequestBody PlanAddDTO addDTO) {
        UserDetails currentUser = UserInfoContext.getCurrentUser();
        boolean ifExisted = checkIfExisted(currentUser.getId(), addDTO.getPlanName());
        if (ifExisted) {
            return CmRes.failure(CmResCode.REPEAT_OPERATION.extra("该广告已存在"));
        }
        AdPlan plan = mapperFacade.map(addDTO, AdPlan.class);
        plan.setUserId(currentUser.getId());
        planService.save(plan);
        return CmRes.success();
    }

    private boolean checkIfExisted(Long userId, String planName) {
        QueryWrapper<AdPlan> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(AdPlan::getUserId, userId)
                .eq(AdPlan::getPlanName, planName);
        AdPlan plan = planService.getOne(wrapper);
        if (null != plan) {
            return true;
        }
        return false;
    }

    @ApiOperation("更新推广计划")
    @PutMapping()
    public CmRes<Void> update(@Valid @RequestBody PlanUpdateDTO updateDTO) {
        UserDetails currentUser = UserInfoContext.getCurrentUser();
        AdPlan oldPlan = planService.getById(updateDTO.getId());
        if (null == oldPlan) {
            return CmRes.failure(CmResCode.DATA_NOT_FOUND);
        }
        if (!oldPlan.getPlanName().equals(updateDTO.getPlanName())) {
            boolean ifExisted = checkIfExisted(currentUser.getId(), updateDTO.getPlanName());
            if (ifExisted) {
                return CmRes.failure(BizResCode.PLAN_IS_REGISTERED);
            }
        }

        AdPlan newPlan = mapperFacade.map(updateDTO, AdPlan.class);
        planService.updateById(newPlan);
        return CmRes.success();
    }

    @ApiOperation("删除推广计划")
    @DeleteMapping()
    public CmRes<Void> delete(@RequestParam List<Long> ids) {
        planService.removeByIds(ids);
        return CmRes.success();
    }

    @ApiOperation("获取推广计划列表")
    @GetMapping("/page")
    public CmRes<CmPage<AdPlan>> page(PlanQueryDTO queryDTO,
                                      @RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
                                      @RequestParam(value = "size", required = false, defaultValue = "10") Integer size) {
        PageHelper.startPage(page, size);
        QueryWrapper<AdPlan> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByDesc(AdPlan::getUpdateTime);
        if (!StringUtils.isEmpty(queryDTO.getPlanName())) {
            wrapper.lambda().like(AdPlan::getPlanName, queryDTO.getPlanName());
        }
        if (!StringUtils.isEmpty(queryDTO.getPlanStatus())) {
            wrapper.lambda().eq(AdPlan::getPlanStatus, queryDTO.getPlanStatus());
        }
        List<AdPlan> planList = planService.list(wrapper);
        return CmRes.success(CmPage.restPage(planList));
    }

    @ApiOperation("根据主键获取推广计划详情")
    @GetMapping("/detail")
    public CmRes<PlanDetailVO> detail(@ApiParam("创意广告id") @RequestParam Long id) {

        AdPlan plan = planService.getById(id);
        PlanDetailVO detailVO = mapperFacade.map(plan, PlanDetailVO.class);
        return CmRes.success(detailVO);
    }
}


